package com.share.nio;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

import org.junit.Test;

public class BlockingNIOTest2 {

	@Test
	public void client() throws Exception{
		SocketChannel sChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 12345));
		FileChannel fChannel = FileChannel.open(Paths.get("1.jpg"), StandardOpenOption.READ);
		ByteBuffer buffer = ByteBuffer.allocate(1024);

		while (fChannel.read(buffer) != -1) {
			buffer.flip();
			sChannel.write(buffer);
			buffer.clear();
		}
		
		//不shutdown，server端就不知道client是否给他发送完数据，就一直阻塞
		sChannel.shutdownOutput();

		int len;
		while ((len = sChannel.read(buffer)) != -1) {
			buffer.flip();
			System.out.println(new String(buffer.array(), 0, len));
			buffer.clear();
		}

		sChannel.close();
		fChannel.close();
	}

	@Test
	public void server() throws Exception{
		ServerSocketChannel ssChannel = ServerSocketChannel.open();
		ssChannel.bind(new InetSocketAddress(12345));

		FileChannel fChannel = FileChannel.open(Paths.get("2.jpg"), StandardOpenOption.WRITE, StandardOpenOption.CREATE);

		ByteBuffer buffer = ByteBuffer.allocate(1024);

		System.out.println("接收前");
		SocketChannel sChannel = ssChannel.accept();
		System.out.println("接收后");

		while (sChannel.read(buffer) != -1) {
			buffer.flip();
			fChannel.write(buffer);
			buffer.clear();
		}

		buffer.put("server返回给client".getBytes());
		buffer.flip();
		sChannel.write(buffer);

		ssChannel.close();
		fChannel.close();
		sChannel.close();
	}

}
